using System;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Unity.VisualScripting;
using Random = UnityEngine.Random;

namespace QFramework.Monk
{
	public partial class EnemyGreator : ViewController,IController
	{
		private float mCurCreateTime;
		private float mCurWaveTime;
		private  WaveSystem mWaveSystem;
		
		private ResLoader mResLoader = ResLoader.Allocate();

		private void Awake()
		{
			mCurCreateTime = 0;
			mCurWaveTime = 0;
			mWaveSystem = this.GetSystem<WaveSystem>();
		}
		
		void Update()
		{

			if (!AppStart.CheckGameState(GameState.GamePlaying))
			{
				return;
			}

			if (Player.Default==null)
			{
				return;
			}
			
			if (mWaveSystem.IsGamePass())
			{
				AppStart.ChangeGameState(GameState.GamePass);
				return;
			}

			if (mWaveSystem.mCurWave==null&&!mWaveSystem.IsLastWave())
			{
				//进入下个回合
				mWaveSystem.NextWave();
			}
			
			if (mWaveSystem.mCurWave!=null)
			{
				mCurWaveTime = mCurWaveTime + Time.deltaTime;
				mCurCreateTime = mCurCreateTime+ Time.deltaTime;

				//创建敌人
				if (mCurCreateTime>=mWaveSystem.mCurWave.Interval)
				{
					mCurCreateTime = 0;

					CreateEnemyObj();
				}
				
				
				//波次结束
				if (mCurWaveTime>=mWaveSystem.mCurWave.Duration)
				{
					mCurWaveTime = 0;
					mWaveSystem.mCurWave = null;
				}
				
			}
			
			
		}

		private void CreateEnemyObj()
		{
			var enemyInfo = mWaveSystem.GetRandomEnemyInfo();
					
			GameObject enemyObj = mResLoader.LoadSync<GameObject>(enemyInfo.Prefab);

			if (enemyObj!=null)
			{
				var randomAngle = Random.Range(0, 360);
				var randomPos = new Vector3(Mathf.Cos(randomAngle * Mathf.Deg2Rad), Mathf.Sin(randomAngle * Mathf.Deg2Rad), 0);
				var pos = Player.Default.transform.position + randomPos * enemyInfo.Radius;

				EnemyBase enemyBase = enemyObj.InstantiateWithParent(this.transform).Position(pos).Show().GetComponent<EnemyBase>();
						
				enemyBase.InitInfo(enemyInfo,mWaveSystem.mCurWave.HpBonus);
				
			}
		}

		void OnDestroy()
		{
			mResLoader.Recycle2Cache();
		}

		public IArchitecture GetArchitecture()
		{
			return AppStart.Interface;
		}
		
	}
}
